package TDengineDB

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

//数据库客户端
type TDengineClient struct {
	user     string        //用户名
	password string        //密码
	url      string        //数据库地址
	basic    string        //签名
	timeout time.Duration //超时时间(秒)
}

//初始化客户端
func NewTDengineClient(ipport string,user string,password string,timeout time.Duration) *TDengineClient {
	basic := base64.StdEncoding.EncodeToString([]byte(fmt.Sprint(user , ":" , password)))
	return &TDengineClient{
		user:     user,
		password: password,
		url:      fmt.Sprint("http://" , ipport , "/rest/sql"),
		basic:    basic,
		timeout: timeout,
	}
}

//http客户端
var httpClient = &http.Client{}

//执行SQL
//sqlConn sql语句
func (c *TDengineClient) Execute(sqlConn string) (*ExecuteResult,error) {
	/*"http://192.168.1.215:6041/rest/sql"*/
	request, err := http.NewRequest("POST", c.url, strings.NewReader(sqlConn))
	request.Header.Add("Authorization", fmt.Sprint("Basic ", c.basic))
	httpClient.Timeout = c.timeout
	response, err := httpClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, errors.New(fmt.Sprint("数据读取异常:", err, "  sql:", sqlConn))
	}
	result := &ExecuteResult{}
	err = json.Unmarshal(body, result)
	if err != nil {
		return nil, errors.New(fmt.Sprint("json序列化异常:", err))
	}
	//执行异常
	if !result.IsSucc() {
		return result, errors.New(fmt.Sprint("状态：", result.Status, "  错误码:", result.Code, "  错误描述：", result.Desc, " sql:", sqlConn))
	}
	return result, nil
}
